#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from optparse import OptionParser,OptionGroup
import sys
import os
# import shutil
import json
# import subprocess

# ===========================================
# Global variables definition
# ===========================================
scriptdir = os.path.dirname(sys.argv[0])
json_file_name = 'test_files.json'
ctest_file_name = 'CTestTestfile.cmake'
run_test_script_name = 'or_run_test.py'

# ===========================================
# Functions definition
# ===========================================

def remove_file(file_path):
    try:
        os.remove(file_path)
        # print("File removed:", file_path)
    except OSError as e:
        print("Error removing the file:", e)

def create_symlink(source, target):
    try:
        os.symlink(source, target)
        # print("Symbolic link created: {} -> {}".format(source, target))
    except OSError as e:
        print("Error creating symbolic link:", e)

def find_files_in_directory(directory, target_file):
    found_files = []

    for dirpath, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            if filename == target_file:
                found_files.append(os.path.join(dirpath, filename))

    return found_files

def is_test_enabled(json_file):
    try:
        # Open the JSON file and load its contents into a Python dictionary
        with open(json_file, 'r') as json_file:
            content = json.load(json_file)
            if 'enabled' in content and content['enabled']:
                return True
        return False
    except IOError as e:
        print(f"Error: {e}")

def prepare_test(file_path, my_array):
    try:
        # Open the file in write mode
        with open(file_path, 'w') as file:
            file.write('# File automatically generated by ' + sys.argv[0] + "\n\n")

            # Convert the array to a string and write it to the file
            for elem in my_array:
                run_test_script = elem + '/' + run_test_script_name

                # Create the run_test script link
                create_link = 1
                if os.path.exists(run_test_script):
                    if os.path.islink(run_test_script):
                        create_link = 0
                    else:
                        remove_file(run_test_script)
                    
                if create_link:
                    create_symlink(os.getcwd() + '/' + scriptdir + '/' + run_test_script_name,run_test_script)

                # Write the line into the ctest file
                cur_str = 'add_test(' + elem + ' ' + run_test_script + ")\n"
                file.write(cur_str)

    except IOError as e:
        print("Error writing to the file:", e)


# ===========================================
# Main entry point
# ===========================================

if __name__ == "__main__":

    usage = "usage: %prog [options]\nRun '%prog --help' to list the options"
    parser = OptionParser(usage=usage)

    # MANDATORY
    mandatory = OptionGroup(parser, "Mandatory Options")
    mandatory.add_option("--test_dir", dest="test_dir",action="store", type="string",
            help="The directory where the tests are located (mandatory)")
    parser.add_option_group(mandatory)

    (options, args) = parser.parse_args()

    if not options.test_dir:
        parser.error('some mandatory options are missing')

    # Search for all test_files.json
    json_files = find_files_in_directory(options.test_dir,json_file_name)
    # print(json_files)

    # Check if test is enable 
    test_to_add = []
    for json_file in json_files:
        if is_test_enabled(json_file):
            test_to_add.append(os.path.dirname((os.path.dirname((json_file)))))
    # print(test_to_add)

    # Add it into the ctest file if enabled and create the link for the script that run the test
    prepare_test(ctest_file_name,test_to_add)